/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Address;
import pojo.User;
import pojo.Userorder;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author A7med Kotb
 */
public class AddressJpaController implements Serializable {

    public AddressJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Address address) throws RollbackFailureException, Exception {
        if (address.getUserorderCollection() == null) {
            address.setUserorderCollection(new ArrayList<Userorder>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User userId = address.getUserId();
            if (userId != null) {
                userId = em.getReference(userId.getClass(), userId.getId());
                address.setUserId(userId);
            }
            Collection<Userorder> attachedUserorderCollection = new ArrayList<Userorder>();
            for (Userorder userorderCollectionUserorderToAttach : address.getUserorderCollection()) {
                userorderCollectionUserorderToAttach = em.getReference(userorderCollectionUserorderToAttach.getClass(), userorderCollectionUserorderToAttach.getId());
                attachedUserorderCollection.add(userorderCollectionUserorderToAttach);
            }
            address.setUserorderCollection(attachedUserorderCollection);
            em.persist(address);
            if (userId != null) {
                userId.getAddressCollection().add(address);
                userId = em.merge(userId);
            }
            for (Userorder userorderCollectionUserorder : address.getUserorderCollection()) {
                Address oldAddressIdOfUserorderCollectionUserorder = userorderCollectionUserorder.getAddressId();
                userorderCollectionUserorder.setAddressId(address);
                userorderCollectionUserorder = em.merge(userorderCollectionUserorder);
                if (oldAddressIdOfUserorderCollectionUserorder != null) {
                    oldAddressIdOfUserorderCollectionUserorder.getUserorderCollection().remove(userorderCollectionUserorder);
                    oldAddressIdOfUserorderCollectionUserorder = em.merge(oldAddressIdOfUserorderCollectionUserorder);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Address address) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Address persistentAddress = em.find(Address.class, address.getId());
            User userIdOld = persistentAddress.getUserId();
            User userIdNew = address.getUserId();
            Collection<Userorder> userorderCollectionOld = persistentAddress.getUserorderCollection();
            Collection<Userorder> userorderCollectionNew = address.getUserorderCollection();
            List<String> illegalOrphanMessages = null;
            for (Userorder userorderCollectionOldUserorder : userorderCollectionOld) {
                if (!userorderCollectionNew.contains(userorderCollectionOldUserorder)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Userorder " + userorderCollectionOldUserorder + " since its addressId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (userIdNew != null) {
                userIdNew = em.getReference(userIdNew.getClass(), userIdNew.getId());
                address.setUserId(userIdNew);
            }
            Collection<Userorder> attachedUserorderCollectionNew = new ArrayList<Userorder>();
            for (Userorder userorderCollectionNewUserorderToAttach : userorderCollectionNew) {
                userorderCollectionNewUserorderToAttach = em.getReference(userorderCollectionNewUserorderToAttach.getClass(), userorderCollectionNewUserorderToAttach.getId());
                attachedUserorderCollectionNew.add(userorderCollectionNewUserorderToAttach);
            }
            userorderCollectionNew = attachedUserorderCollectionNew;
            address.setUserorderCollection(userorderCollectionNew);
            address = em.merge(address);
            if (userIdOld != null && !userIdOld.equals(userIdNew)) {
                userIdOld.getAddressCollection().remove(address);
                userIdOld = em.merge(userIdOld);
            }
            if (userIdNew != null && !userIdNew.equals(userIdOld)) {
                userIdNew.getAddressCollection().add(address);
                userIdNew = em.merge(userIdNew);
            }
            for (Userorder userorderCollectionNewUserorder : userorderCollectionNew) {
                if (!userorderCollectionOld.contains(userorderCollectionNewUserorder)) {
                    Address oldAddressIdOfUserorderCollectionNewUserorder = userorderCollectionNewUserorder.getAddressId();
                    userorderCollectionNewUserorder.setAddressId(address);
                    userorderCollectionNewUserorder = em.merge(userorderCollectionNewUserorder);
                    if (oldAddressIdOfUserorderCollectionNewUserorder != null && !oldAddressIdOfUserorderCollectionNewUserorder.equals(address)) {
                        oldAddressIdOfUserorderCollectionNewUserorder.getUserorderCollection().remove(userorderCollectionNewUserorder);
                        oldAddressIdOfUserorderCollectionNewUserorder = em.merge(oldAddressIdOfUserorderCollectionNewUserorder);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = address.getId();
                if (findAddress(id) == null) {
                    throw new NonexistentEntityException("The address with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Address address;
            try {
                address = em.getReference(Address.class, id);
                address.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The address with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Userorder> userorderCollectionOrphanCheck = address.getUserorderCollection();
            for (Userorder userorderCollectionOrphanCheckUserorder : userorderCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Address (" + address + ") cannot be destroyed since the Userorder " + userorderCollectionOrphanCheckUserorder + " in its userorderCollection field has a non-nullable addressId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            User userId = address.getUserId();
            if (userId != null) {
                userId.getAddressCollection().remove(address);
                userId = em.merge(userId);
            }
            em.remove(address);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Address> findAddressEntities() {
        return findAddressEntities(true, -1, -1);
    }

    public List<Address> findAddressEntities(int maxResults, int firstResult) {
        return findAddressEntities(false, maxResults, firstResult);
    }

    private List<Address> findAddressEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Address.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Address findAddress(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Address.class, id);
        } finally {
            em.close();
        }
    }

    public int getAddressCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Address> rt = cq.from(Address.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
